//************************************************************************
//Developed by Guo Ming Li 2009/2010
//Source code:
//  The source code may be freely modified or used but this credit section may not be removed 
//  The original author must be notified of any modifications plus a copy of 
//  the changed source code
//Contact info: mailto://gming.li@gmail.com
//************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.BizTalk.ExplorerOM;


namespace GML.BizTalk.OperationManager.Library
{
    public class ReceiveLocations
    {
        public static bool EnableAllReceiveLocation(string btsDbServerName, string btsMgntDbName, string sBtsAppName, out Exception ex)
        {
            BtsCatalogExplorer root = new BtsCatalogExplorer();
            List<ReceivePort> receivePorts = new List<ReceivePort>();

            try
            {
                root.ConnectionString = Helper.GetConnectionString(btsDbServerName, btsMgntDbName);

                foreach (ReceivePort receivePort in root.ReceivePorts)
                {
                    if (receivePort.Application.Name.Equals(sBtsAppName))
                    {
                        receivePorts.Add(receivePort);
                    }
                }
                foreach (ReceivePort receivePort in receivePorts)
                {
                    foreach (ReceiveLocation receiveLocation in receivePort.ReceiveLocations)
                    {
                        if (receiveLocation.Enable == false)
                        {
                            receiveLocation.Enable = true;
                        }
                    }
                }

                //Try to commit the changes made so far. 
                root.SaveChanges();
                ex = null;
                return true;
            }
            catch (Exception e)//If it fails, roll-back everything we have done so far
            {
                System.Diagnostics.Debug.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
                Logger.doLog(Guid.NewGuid().ToString(), e.Message, Logger.ServerityLevel.ERROR);
                Logger.doLog(Guid.NewGuid().ToString(), e.StackTrace, Logger.ServerityLevel.ERROR);
                root.DiscardChanges();
                ex = e;
                return false;
            }
            finally
            {
                if (root != null) root.Dispose();
                root = null;
                receivePorts = null;
            }
        }

    }
}
